package classes;

import java.util.Iterator;
import java.util.Random;

import classes.DDict;

public class Hist<ktype> extends DDict<ktype, Double> {
	/**
	 * Histogram of values. The default value is 0d
	 */
	private static final long	serialVersionUID = 1L;
	private static final Double	zero = new Double(0D);
	private static final Random	rnd = new Random();

	private double sum = 0d;

	public Hist() {
		super(zero);
	}

	@Override
	public Double put(ktype key, Double value) {
		sum -= get(key);
		if (value==null || value.compareTo(zero) <= 0) {
			// Setting value to zero. Nothing to add to the sum
			return super.remove(value);
		} else {
			// Value is positive. We must add to the sum
			sum += value;
			return super.put(key, value);
		}
	}

	public Double getSum() {
		return new Double(sum);
	}

	public ktype randomKey() {
		//
		// This will choose a random key from the histogram.
		// If there are no keys present then null is returned
		//
		ktype	choice = null;
		if (size()>0) {
			double				threshold	= rnd.nextDouble()*getSum();
			double				area		= 0D;
			Iterator<ktype>		itr = this.keySet().iterator();
			while(itr.hasNext() && area <= threshold) {
				choice = itr.next();
				area += this.get(choice);
			}
		}
		return choice;
	}

	public Double getShare(ktype K) {
		//
		// Returns the percentage share of the total weight for this key
		//
		if (this.isEmpty()) {
			return zero;
		} else {
			return get(K) / getSum();
		}
	}
}
